/*
 * Alloy Analyzer
 * Copyright (c) 2002 Massachusetts Institute of Technology
 *
 * The Alloy Analyzer is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * The Alloy Analyzer is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with the Alloy Analyzer; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 */

package alloy.semantic;

/*
 * Alloy Analyzer
 * Copyright (c) 2001
 * Massachusetts Institute of Technology
 *
 * Class: Scope
 * owner: msridhar
 * Interface status: unstable
 * Implementation status: unstable
 *
 *
 * Abstract data type representing a local scope
 * A scope contains mappings between variable names and types
 */

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;

import alloy.ast.Decl;
import alloy.ast.Decls;
import alloy.ast.LeafId;
import alloy.ast.Variable;
import alloy.transform.LeafIdMap;
import alloy.type.RelationType;
import alloy.type.UnionType;
import alloy.util.Dbg;

public class LocalScope implements Cloneable {


    /** mapping from String names to RelationType type or ArrayList of types
        if there are multiple matches */
    private HashMap _nameToType;

    /** LocalScope parents of this */
    private ArrayList _parents;

    public LocalScope() {
        _nameToType = new HashMap();
        _parents = new ArrayList();
    }

    /**
     * create a new local scope from typed decls
     */
    public static LocalScope genScopeFromDecls(Decls decls) {
        LocalScope ret = new LocalScope();
        Iterator declIter = decls.getDeclIter();
        while (declIter.hasNext()) {
            Decl decl = (Decl)declIter.next();
            UnionType curType = decl.getExpr().getType();
            Iterator varIter = decl.getVariables().getVariableIter();
            while (varIter.hasNext()) {
                String varString = ((Variable)varIter.next()).nodeString();
                try {
                    ret.addMapping(varString, curType);
                } catch (AlreadyMappedException ame) { Dbg.fatal("can't happen"); }
            }
        }
        return ret;
    }
    
    /**
     * add a parent to this
     * @param parent_ the new parent
     */
    public void addParent(LocalScope parent_) {
        _parents.add(parent_);
    }

    /**
     * get the parents of this
     * @return an iteration of the parents
     */
    public Iterator getParents() {
        return _parents.iterator();
    }

    /** gets the names bound by this */
    public Iterator getBoundNames() {
        return _nameToType.keySet().iterator();
    }
    
    public LocalScope copy() {
        LocalScope newLocalScope = null;
        try {
            newLocalScope = (LocalScope)this.clone();
        } catch (CloneNotSupportedException cnse) {}
        newLocalScope._nameToType = new HashMap(_nameToType);
        newLocalScope._parents = new ArrayList();
        return newLocalScope;
    }
    
     /**
     * add a name-to-type mapping to this
     * @param name_ the name to be mapped
     * @param type_ the type to map to
     */
    public void addMapping(String name_, UnionType type_) throws AlreadyMappedException {
        Dbg.check(name_ != null, "attempt to map null name");
        Dbg.check(type_ != null, "attempt to map to null type");
        // check if name is already mapped
        if (_nameToType.containsKey(name_)) {
            throw new AlreadyMappedException();
        } else {
            // add a mapping from name_ to type_
            _nameToType.put(name_, type_);
        }
    }
        
    /**
     * try to find a type associated with a name from this
     * or the ancestors of this
     * @param name_ the name whose type is being requested
     * @return the found type, or <code>null</code> if no type was found
     */
    public UnionType lookupType(String name_) {
       // see if name is mapped in this
        UnionType mappedTo = getType(name_);
        if (mappedTo == null) { // not mapped in this
            // lookup in parents
            Iterator parentIter = _parents.iterator();
            while (parentIter.hasNext()) {
                LocalScope curParent = (LocalScope)parentIter.next();
                mappedTo = curParent.lookupType(name_);
                if (mappedTo != null) break;
            }
        } else {
            //Dbg.info("lookup " + name_);
            //Dbg.info(this.toString());
        }
        return mappedTo;
    }

    /**
     * Generates a LeafIdMap mapping each name bound in this scope
     * to their new ids.  This method should be invoked
     * after all names have been added to the scope.
     * @param parent_ parent for the new map, may be null
     */
    public LeafIdMap generateLeafIdMapping(LeafIdMap parent_) {
        //Dbg.info("generating leaf id mapping");
        LeafIdMap map = new LeafIdMap(parent_);
        Iterator names = getBoundNames();
        while (names.hasNext()) {
            String name = (String)names.next();
            //Dbg.info("generating id for " + name);
            map.put(name, new LeafId());
        }
        return map;
    }
    
    /**
     * get a type associated with a name from this
     * @param name_ the name whose type is being requested
     * @return the {@link RelationType}
     * @throw MultipleMappingsException requested name maps to multiple types
     */
    private UnionType getType(String name_) {
        return (UnionType)_nameToType.get(name_);
    }

    public String toString() { return _nameToType.toString() + " => " + _parents.toString(); }
} // LocalScope












